package br.org.ifrr.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.org.ifrr.model.Empenho;
import br.org.ifrr.repository.filter.EmpenhoFilter;

public class Empenhos implements Serializable {

	private static final long serialVersionUID = 1L;

	@Inject
	private EntityManager manager;

	public Empenho guardar(Empenho empenho) {
		return manager.merge(empenho);
	}

	public Empenho porId(Long id) {
		return manager.find(Empenho.class, id);
	}

	public Empenho porNumeroEmpenho(String empenhoNumero) {

		try {
			return manager.createQuery("from Empenho where upper(empenhoNumero) = :empenhoNumero", Empenho.class)
					.setParameter("empenhoNumero", empenhoNumero.toUpperCase()).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Empenho> filtrados(EmpenhoFilter filtro) {
		Session session = manager.unwrap(Session.class);
		Criteria criteria = session.createCriteria(Empenho.class);

		if (StringUtils.isNotBlank(filtro.getNome())) {
			criteria.add(Restrictions.ilike("empenhoNumero", filtro.getNome(),
					MatchMode.ANYWHERE));
		}
		
		if (StringUtils.isNotBlank(filtro.getProcesso())) {
			criteria.add(Restrictions.ilike("processo", filtro.getProcesso(),
					MatchMode.EXACT));
		}

		return criteria.addOrder(Order.asc("empenhoNumero")).list();
	}

	public List<Empenho> porEmpenho(String empenhoNumero) {

		return this.manager.createQuery("from Empenho where upper(empenhoNumero) like :empenhoNumero",	Empenho.class)
				.setParameter("empenhoNumero", empenhoNumero.toUpperCase() + "%").getResultList();
	}
}
